package com.manager.common.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.manager.common.vo.ResultVO;
import com.manager.common.vo.UploadFileVO;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@SuppressWarnings("all")
public class LargeFileHttpUploadUtils {

	private static String basePath = "";

	private static String downloadbaseUrl = "";
	
	private static String ip;
	
	private static String port;
	
	private static String projectName;
	
	static {
		basePath = System.getProperty("user.dir") + File.separator + "..";
		downloadbaseUrl = "http://";
	}
	
	public static String getUploadFileSavePath() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dirName = dateFormat.format(new Date());
		String resultDirPath = basePath + File.separator + "uploadFiles" + File.separator + dirName;
		File f = new File(resultDirPath);
		if (!f.exists()) {
			f.mkdirs();
		}
		return f.getAbsolutePath();
	}

	public static String getBasePath() {
		return basePath;
	}

	public static void setBasePath(String basePath) {

		File file = new File(basePath);
		if(!file.exists()){
			file.mkdirs();
		}
		LargeFileHttpUploadUtils.basePath = file.getAbsolutePath();
	}

	public static String getDownloadbaseUrl() {
		return downloadbaseUrl;
	}

	public static void setDownloadbaseUrl(String host, String port, String projectName) {
		LargeFileHttpUploadUtils.downloadbaseUrl ="http://" + host + ":" + port +  File.separator
				+ "manager" + File.separator + projectName + File.separator;
		LargeFileHttpUploadUtils.ip = host;
		LargeFileHttpUploadUtils.port = port;
		LargeFileHttpUploadUtils.projectName = projectName;
	}

	/***
	 * 出现跨域问题添加<br />
	 * response.setHeader("Access-Control-Allow-Origin", "*");
	 * 
	 */
	public static ResultVO uploadFile(HttpServletRequest request, MultipartFile file) {

		String uuid = request.getParameter("uuid");
		String name = request.getParameter("name");
		String index = request.getParameter("index");
		int count = request.getParameter("count") == null ? 0 : Integer.parseInt(request.getParameter("count"));
		String path = LargeFileHttpUploadUtils.getBasePath() + File.separator + uuid + "_temp" ;

		BufferedInputStream buff = null;
		FileOutputStream out = null;
		File f = null;

		try {

			buff = new BufferedInputStream(file.getInputStream());
			f = new File(path + File.separator + index);

			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdirs();
			}

			if (f.exists()) {
				f.delete();
			}

			out = new FileOutputStream(f);
			byte[] read = new byte[1024];
			int mark = 0;

			while ((mark = buff.read(read)) != -1) {
				out.write(read, 0, mark);
			}
			int successIndexs = new File(path).listFiles().length;
			return ResultVO.success(new UploadFileVO(Integer.valueOf(index),count,successIndexs,uuid,false));

		} catch (Exception e) {
			e.printStackTrace();
			if(f != null){
				f.delete();
			}
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (buff != null) {
				try {
					buff.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return ResultVO.failed(new UploadFileVO(Integer.valueOf(index),count,0,uuid,false));
	}

	/***
	 * 出现跨域问题添加<br />
	 * response.setHeader("Access-Control-Allow-Origin", "*");
	 * 
	 * @throws Exception
	 * 
	 */
	public static ResultVO meragePartFile(HttpServletRequest request) throws Exception {
		String jsonStr = request.getParameter("jsonStr");
		String path = LargeFileHttpUploadUtils.getBasePath();
		JSONArray ja = JSONArray.fromObject(jsonStr);
		List<JSONObject> resultList = new ArrayList<JSONObject>();
		List<File> encryptFileList = new ArrayList<>();

		for (int j = 0; j < ja.size(); j++) {
			String message = "";
			String name = ja.getJSONObject(j).getString("name");
			String uuid = ja.getJSONObject(j).getString("uuid");
			String total = ja.getJSONObject(j).getString("total");

			String resultFilePath = LargeFileHttpUploadUtils.getUploadFileSavePath() + File.separator + uuid
					+ name.substring(name.lastIndexOf("."), name.length());
			File resultFile = new File(resultFilePath);
			FileChannel fc = new FileOutputStream(resultFile, true).getChannel();
			String tempDir = path + File.separator + uuid + "_temp";

			for (int i = 0; i < Integer.parseInt(total); i++) {
				File e = new File(tempDir + File.separator + i);
				if (!e.exists()) {
					message = "临时文件不存在!";
					System.out.println(message);
					break;
				}
				FileChannel tempFc = new FileInputStream(e).getChannel();
				fc.transferFrom(tempFc, fc.size(), tempFc.size());
				tempFc.close();
			}

			fc.close();

			encryptFileList.add(resultFile);

			JSONObject resultObject = new JSONObject();

			resultObject.put("fileName",name);
			resultObject.put("filePath",
					resultFile.getAbsolutePath()
							.substring(LargeFileHttpUploadUtils.getBasePath().length(), resultFile.getAbsolutePath().length())
							.replaceAll("\\\\", "/"));
			resultObject.put("uuidFileName", resultFile.getName());
			resultObject.put("fileSize", LargeFileUtils.reckonFileSize(resultFile.length()));
			resultObject.put("fileSuffix", resultFile.getName().subSequence(resultFile.getName().lastIndexOf(".") + 1,
					resultFile.getName().length()));
			resultList.add(resultObject);

			LargeFileUtils.deleteMultiLevelFiles(tempDir);

		}
		return ResultVO.success(resultList);
	}
}
